package web;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import IO.Settings;

public class SMS 
{
	public static String sender = "Sonny"; 
	public static String sendMsg(String message)
	{
		return sendMsg(Settings.getSetting("phoneNumber"), message);
	}
	public static String sendMsg(String phoneNumber, String message)
	{
		String returnString = null;
		
		if(phoneNumber.length() != 10)
		{	
			returnString = "Phone number should have 10 digits";
		}
		int contentSize = SMS.sender.toString().length() + message.length();
		if(contentSize > 140)
		{
			returnString = "Message should be of length "+(140-SMS.sender.length())+" or shorter.";
		}
		if(returnString == null)
		{
			returnString = SMS.postData(phoneNumber, message, contentSize);
		}
		return returnString;
	}
	private static String prepContent(String key, String value)
	{
		String returnString = "";
		try{
			returnString = URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
		}
		catch(Exception e){}
		return returnString;
	}
	private static String postData(String phoneNumber, String message, Integer contentSize)
	{
		String returnString = phoneNumber+" Not delivered.";
		try {
		    // Construct data
		    String data = prepContent("subname", phoneNumber.toString());
		    data += "&" + prepContent("msgtext", message);
		    data += "&" + prepContent("size", contentSize.toString());
		    data += "&" + prepContent("sig", SMS.sender);
		    data += "&" + prepContent("submit", "SEND");
		    
		    // Send data
		    URL url = new URL("http://sms.sasktel.com/cgi-bin/pagepage");
		    URLConnection conn = url.openConnection();
		    conn.setDoOutput(true);
		    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		    wr.write(data);
		    wr.flush();

		    // Get the response
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    String line = "";
		    String buffer = "";
		    while ((line = rd.readLine()) != null){
		    	buffer += line;
		    }
		    wr.close();
		    rd.close();
		    Pattern p = Pattern.compile("Message for ([0-9]*) was (.*) on (.*) at ([0-9]*:[0-9]*:[0-9]*)");
		    Matcher m = p.matcher(buffer);
		    while(m.find())
		    {
		    	returnString = m.group(1)+" "+m.group(2)+" "+m.group(3)+" "+m.group(4);	
		    }
		} catch (Exception e) {
		}
		return returnString;
	}
}
